<template>
  <div style="background: #fff">
    <a-tabs @change="selectTabs">
      <a-tab-pane key="wxMpConfig" tab="微信公众号消息配置">
        <div class="account-settings-info-view">
          <a-form ref="wxMpConfigFormModel" :model="vdata.configData" layout="vertical" :rules="vdata.wxMpConfigRules">
            <a-row justify="start" type="flex" style="margin-top: 20px">
              <a-col :span="17" :offset="1">
                <a-form-item label="微信公众号二维码" name="wxmpUrl">
                  <GzUpload v-model:src="vdata.configData.wxmpUrl" bizType="wxFile" fileType="img" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="微信公众号AppId" name="wxAppId">
                  <a-input v-model:value="vdata.configData.wxAppId" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="微信公众号AppSecret" name="wxAppSecret">
                  <a-input v-model:value="vdata.configData.wxAppSecret" :placeholder="vdata.configDataDesen.wxAppSecret || '请填写'" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="模板消息ID" name="paySuccMsgTemplateId">
                  <a-input v-model:value="vdata.configData.paySuccMsgTemplateId" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="OAuth2地址（置空则使用微信官方）" name="mchAuthRedirectUrl">
                  <a-input v-model:value="vdata.configData.mchAuthRedirectUrl" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="备注信息" name="paySuccMsgTemplateContentRemark">
                  <a-input v-model:value="vdata.configData.paySuccMsgTemplateContentRemark" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <!-- <a-col :span="17" :offset="1">
                <a-form-item label="微信校验文件（上传自动解析）">
                  <GzUpload v-model:upload="vdata.wx3rdCheckFileResult" :action="upload.wx3rdCheckFile">
                    <template #uploadSlot="{loading}">
                      <a-button style="margin-top:5px;"> <a-icon :type="loading ? 'loading' : 'upload'" /> {{ loading ? '正在上传' : '点击上传' }} </a-button>
                    </template>
                  </GzUpload>
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="微信校验文件名" name="wxCheckFileName">
                  <a-input v-model:value="vdata.wxMpConfigData.wxCheckFileName" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="微信校验文件内容" name="wxCheckFileValue">
                  <a-input v-model:value="vdata.wxMpConfigData.wxCheckFileValue" autocomplete="off" />
                </a-form-item>
              </a-col> -->
              <a-col :span="22" :offset="1">
                <p class="tem-title">配置指南：</p>
                <p class="tem-msg">1. 微信授权域名，请配置：{{ vdata.payUrl }}</p>
                <p class="tem-msg">2. 将服务器IP配置到微信平台IP白名单</p>
                <p class="tem-msg">3. 模板消息编号为：OPENTM408727351，微信中申请（IT科技-互联网|电子商务-收款成功通知）</p>
              </a-col>
            </a-row>
            <a-form-item class="bottom-btn">
              <a-button v-if="$access('ENT_PUSH_CONFIG_EDIT')" :disabled="!vdata.isEdit" type="primary" :loading="vdata.btnLoading" @click="confirm"><check-circle-outlined />确认更新</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>

      <a-tab-pane key="appPushConfig" tab="app推送配置">
        <div class="account-settings-info-view">
          <a-form ref="appPushConfigFormModel" :model="vdata.configData" layout="vertical" :rules="vdata.appPushConfigRules">
            <a-row justify="start" type="flex" style="margin-top: 20px">
              <a-col :span="8" :offset="1">
                <a-form-item label="uniPush_appId" name="uniPushAppId">
                  <a-input v-model:value="vdata.configData.uniPushAppId" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="uniPush_appKey" name="uniPushAppKey">
                  <a-input v-model:value="vdata.configData.uniPushAppKey" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="uniPush_masterSecret" name="uniPushMasterSecret">
                  <a-input v-model:value="vdata.configData.uniPushMasterSecret" :placeholder="vdata.configDataDesen.uniPushMasterSecret || '请填写'" autocomplete="off" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item class="bottom-btn">
              <a-button v-if="$access('ENT_PUSH_CONFIG_EDIT')" :disabled="!vdata.isEdit" type="primary" :loading="vdata.btnLoading" @click="confirm"><check-circle-outlined />确认更新</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>

      <a-tab-pane key="baiduBceConfig" tab="百度语音配置">
        <div class="account-settings-info-view">
          <a-form ref="baiduBceConfigFormModel" :model="vdata.configData" layout="vertical" :rules="vdata.baiduBceConfigRules">
            <a-row justify="start" type="flex" style="margin-top: 20px">
              <a-col :span="8" :offset="1">
                <a-form-item label="百度语音AppKey" name="baiduBceAppKey">
                  <a-input v-model:value="vdata.configData.baiduBceAppKey" placeholder="请填写" autocomplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="1">
                <a-form-item label="百度语音AppSecret" name="baiduBceAppSecret">
                  <a-input v-model:value="vdata.configData.baiduBceAppSecret" :placeholder="vdata.configDataDesen.baiduBceAppSecret || '请填写'" autocomplete="off" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item class="bottom-btn">
              <a-button v-if="$access('ENT_PUSH_CONFIG_EDIT')" :disabled="!vdata.isEdit" type="primary" :loading="vdata.btnLoading" @click="confirm"><check-circle-outlined />确认更新</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script setup lang="ts">
import {$getConfigs,$updateSysConfigs} from '@/api/sysManage/sysConfig/index'
import { ref, reactive, onMounted, getCurrentInstance, watch } from 'vue'

  const { $infoBox,$access } = getCurrentInstance()!.appContext.config.globalProperties

  const wxMpConfigFormModel = ref()
  const appPushConfigFormModel = ref()
  const baiduBceConfigFormModel = ref()


// 通用处理脱敏数据逻辑
function ruleProcessByDesen(rule, value, callback){
  if (!vdata.configDataDesen[rule.field] && !value) {
    return Promise.reject(new Error(rule.message))
  }
  return Promise.resolve()
}

  const vdata = reactive ({
    isEdit:$access('ENT_PUSH_CONFIG_EDIT'),
    btnLoading: false,
    groupKey: 'wxMpConfig',
    configData: {} as any, // 配置保存对象
    configDataDesen: {} as any, // 脱敏数据
    wx3rdCheckFileResult: '', // 微信三方校验文件解析结果
    payUrl: '',
    wxMpConfigRules: {
      wxmpUrl: [{ required: true, message: '请上传微信公众号二维码', trigger: 'blur' }],
      wxAppId: [{ required: true, message: '请填写微信公众号AppId', trigger: 'blur' }],
      wxAppSecret: [{ required: true, message: '请填写微信公众号wxAppSecret', trigger: 'blur', validator: ruleProcessByDesen }],
      paySuccMsgTemplateId: [{ required: true, message: '请填写模板消息ID', trigger: 'blur' }]
    },
    appPushConfigRules: {
      uniPushAppId: [{ required: true, message: '请填写uniPush_appId', trigger: 'blur' }],
      uniPushAppKey: [{ required: true, message: '请填写uniPush_appKey', trigger: 'blur' }],
      uniPushMasterSecret: [{ required: true, message: '请填写uniPush_masterSecret', trigger: 'blur', validator: ruleProcessByDesen }]
    },
    baiduBceConfigRules: {
      baiduBceAppKey: [{ required: true, message: '请填写百度语音AppKey', trigger: 'blur' }],
      baiduBceAppSecret: [{ required: true, message: '请填写百度语音AppSecret', trigger: 'blur', validator: ruleProcessByDesen }]
    }
  })

  onMounted(()=>{
    detail()

    $getConfigs('applicationConfig').then(res => {
      res.forEach(item => {
        if(item.configKey === 'paySiteUrl') {
          vdata.payUrl = item.configVal.toString().replace('http://', '').replace('https://', '')
        }
      })
    })
  })

  function detail () { // 获取基本信息
    $getConfigs(vdata.groupKey).then(res => {

      vdata.configData = {}  // 重置配置信息
      vdata.configDataDesen = {}

      vdata.groupKey = res[0].groupKey

      res.forEach(item => {
        vdata.configData[item.configKey] = item.configVal
        vdata.configDataDesen[item.configKey] = item.configValDesen
      })
    })
  }

  /* watch(() => vdata.wx3rdCheckFileResult, (nv, ov) => {
    vdata.wxMpConfigData.wxCheckFileName = nv['fileOriginName']
    vdata.wxMpConfigData.wxCheckFileValue = nv['value']
  }) */

  function selectTabs (key) { // 清空必填提示
    if (key) {
      vdata.groupKey = key
      detail()
    }
  }

  // 确认更新
  function confirm (e) {
    if ('wxMpConfig' === vdata.groupKey) {

      wxMpConfigFormModel.value.validate().then(valid => {
        saveConfig('确认修改公众号提醒配置吗？')
      })

    } else if ('appPushConfig' === vdata.groupKey) {

      appPushConfigFormModel.value.validate().then(valid => {
        saveConfig('确认修改app推送配置吗？')
      })

    } else if ('baiduBceConfig' === vdata.groupKey) {

      baiduBceConfigFormModel.value.validate().then(valid => {
        saveConfig('确认修改百度语音配置吗？')
      })

    }
  }

  function saveConfig(msg) {
    $infoBox.confirmPrimary(msg, '', () => {
      vdata.btnLoading = true // 打开按钮上的 loading
      $updateSysConfigs(vdata.groupKey, vdata.configData).then(res => {
        $infoBox.message.success('修改成功')
        vdata.btnLoading = false
      }).catch(res => {
        vdata.btnLoading = false
      })
    })
  }

</script>
<style lang="less" scoped>
  .bottom-btn{
    /deep/ div{
      display: flex;
      justify-content: center;
    }
  }
</style>
